package com.example.twoDataSource.aspect;

import com.example.twoDataSource.context.DataSourceContextHolder;
import com.example.twoDataSource.inter.DS;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Order (0)
public class DynamicDataSourceAspect
{

    @Pointcut("@annotation(com.example.twoDataSource.inter.DS)")
    public void dataSourceSwitchPointCut() {}

    @Around("dataSourceSwitchPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        DS annotation = signature.getMethod().getAnnotation(DS.class);
        if (annotation != null && !"".equals(annotation.value())) {
            DataSourceContextHolder.setDB(annotation.value()); // 切换数据源
        }
        try {
            return point.proceed(); // 执行方法
        } finally {
            DataSourceContextHolder.clearDB(); // 清除数据源类型，恢复默认
        }
    }
}
